package pulpfizz.pulp.body;

import org.jbox2d.collision.CircleShape;
import org.jbox2d.collision.PolygonShape;
import org.jbox2d.common.Vec2;
import org.jbox2d.dynamics.Body;

import pulpcore.image.Colors;
import pulpcore.image.CoreGraphics;
import pulpcore.math.CoreMath;
import pulpcore.math.Transform;
import pulpcore.sprite.Sprite;

/**
 * Draws Body objects using the internal Pulpcore drawing routines.
 * Created by will
 * Date: Apr 23, 2008 6:22:44 AM
 */
public class PulpBodySprite extends BodySpriteOld {

    private int drawColor;

    public PulpBodySprite(Body body, PhysicsLayer physics, int color) {
        super(body, physics);
        this.drawColor = color;
        this.setAnchor(Sprite.CENTER);
    }

    public PulpBodySprite(Body body, PhysicsLayer physics) {
        this(body,physics, Colors.WHITE);
    }
    
    /** (from ImageSprite) */
    protected void drawSprite(CoreGraphics g) {
        g.setColor(drawColor);

        float sc = physics.getScaling();

        g.pushTransform();
        Transform t = g.getTransform();

        // Translate draw coordinates to make 0,0 the center of the image.
        t.translate(width.getAsFixed()/2,height.getAsFixed()/2);

        // Translate the draw coordinates to the position offset.
        t.translate(-CoreMath.toFixed(offsetX),-CoreMath.toFixed(offsetY));

        // Scale draw coordinates from physics world to image coordinates.
        // y axis is inverted, and coordScale is multiplied to scale up the small floating point coordinates to be able
        // to use integer draw methods correctly.
        t.scale(CoreMath.toFixed(sc),CoreMath.toFixed(-sc));
        
        org.jbox2d.collision.Shape s = body.getShapeList();
        while (s != null) {
            switch (s.getType()) {
                case CIRCLE_SHAPE:
                    CircleShape c = (CircleShape) s;
                    float rad = c.m_radius;
                    g.setColor(drawColor);
                    //TODO: Replace with fillCircle
                    g.fillRect(-rad,-rad,rad*2,rad*2);
                    g.setColor(Colors.BLACK);
//                    g.drawRect(-rad,-rad,rad*2,rad*2);
                    g.drawLine(0,0,0,-rad);
                    break;

                case POLYGON_SHAPE:
                    PolygonShape p = (PolygonShape) s;
                    Vec2[] vertices = p.getVertices();
                    int vertexCount = p.getVertexCount();
                    for (int i = 1; i < vertexCount; i++) {
                        g.drawLine(vertices[i-1].x,vertices[i-1].y,vertices[i].x,vertices[i].y);
                    }
                    g.drawLine(vertices[vertexCount-1].x,vertices[vertexCount-1].y,vertices[0].x,vertices[0].y);
                    //TODO: Polygon fill
                    break;
            }
            s = s.getNext();
        }
        g.popTransform();
    }
}